package com.leo.biz.service.pub;

import com.google.gson.Gson;
import com.leo.db.mapper.KrecordEverydayMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * Created by leo on 2016/6/29.
 */
@Service
public class DaoCenter {

    @Autowired
    private KrecordEverydayMapper krecordEverydayMapper;

    /**
     * 对数据表tablename，增加一个对象
     */

    public <T> List<T> queryResult(Class<T> objClass,String condition){
        String _str=objClass.getName();
        String[] _temp=_str.split("\\.");
        String className=_temp[_temp.length-1];
        String _tableName=getTableNameByPoName(className);

        List<Map<String,Object>> li=krecordEverydayMapper.getTableInfo(_tableName, " " + condition + " ");
        List<T> retList=new LinkedList<>();
        Gson gson=new Gson();
        String strJson;
        for(int i=0;i<li.size();i++)
        {
            strJson=gson.toJson(li.get(i));
            T temp=gson.fromJson(strJson, objClass);
            retList.add(temp);
        }
        return retList;
    }

    public <T> int delteResult(Class<T> objClass,String condition){
        String _str=objClass.getName();
        String[] _temp=_str.split("\\.");
        String className=_temp[_temp.length-1];
        String _tableName=getTableNameByPoName(className);

        int ret=krecordEverydayMapper.delTableRecord(_tableName, " " + condition+" ");

        return ret;
    }

    public <T> int insertResult(T obj){
        String _str=obj.getClass().getName();
        String[] _temp=_str.split("\\.");
        String className=_temp[_temp.length-1];
        String _tableName=getTableNameByPoName(className);
        String[] filedNames=getFiledName(obj);
        String[] filedVal=getFieldStrValueByName(filedNames, obj);

        String desStr="";
        String valStr="";
        int ret=0;
        for(int i=0;i<filedVal.length;i++)
        {
            if(filedVal[i]!=null) {
                desStr = desStr + filedNames[i] + ",";
                valStr = valStr + "'" + filedVal[i] + "'" + ",";
            }
        }
        desStr=desStr.substring(0,desStr.length()-1);
        valStr=valStr.substring(0,valStr.length()-1);
        String str=_tableName+" ("+desStr+")VALUES("+valStr+")";
        try {
             ret = krecordEverydayMapper.insertRow(str);
        } catch (Exception e) {
            //e.printStackTrace();
        }
        return ret;
    }

    public <T> int insertMultiResult(List<T> objlist){
        int ret=0;
        String _str=objlist.get(0).getClass().getName();
        String[] _temp=_str.split("\\.");
        String className=_temp[_temp.length-1];
        String _tableName=getTableNameByPoName(className);
        String[] filedNames=getFiledName(objlist.get(0));
        String desStr="";
        for(int i=0;i<filedNames.length;i++)
        {
            desStr = desStr + filedNames[i] + ",";
        }
        desStr=desStr.substring(0,desStr.length()-1);
        String mutiValStr="";
        for(int i=0;i<objlist.size();i++)
        {
            String[] filedVal=getFieldStrValueByName(filedNames, objlist.get(i));
            String valStr=getSqlValueStr(filedVal);
            mutiValStr=mutiValStr+valStr+",";
        }
        mutiValStr=mutiValStr.substring(0,mutiValStr.length()-1);
        String sql=_tableName+" ("+desStr+")VALUES "+mutiValStr;

        try {
            ret = krecordEverydayMapper.insertRow(sql);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret;
    }

    public String getSqlValueStr(String [] valList)
    {
        String ret="(";
        for(int i=0;i<valList.length;i++)
        {
            if(valList[i]!=null) {
                ret = ret + "'" + valList[i] + "'" + ",";
            }else
            {
                ret = ret + "NULL" + ",";
            }
        }
        ret=ret.substring(0,ret.length()-1)+")";
        return ret;
    }

    public String getTableNameByPoName(String className){
        StringBuilder _temp=new StringBuilder();
        for(int i=0;i<className.length();i++)
        {
            if(Character.isUpperCase(className.charAt(i))==true && i!=0)
            {
                _temp.append("_");
            }
            _temp.append(className.charAt(i));
        }
        return _temp.toString();
    }


    /**
     * 获取对象属性，返回一个字符串数组
     *
     * @param  o 对象
     * @return String[] 字符串数组
     */
    private String[] getFiledName(Object o)
    {
        try
        {
            Field[] fields = o.getClass().getDeclaredFields();
            String[] fieldNames = new String[fields.length];
            for (int i=0; i < fields.length; i++)
            {
                fieldNames[i] = fields[i].getName();
            }
            return fieldNames;
        } catch (SecurityException e)
        {
            e.printStackTrace();
            System.out.println(e.toString());
        }
        return null;
    }


    /*
     * 使用反射根据属性名称获取属性值
     *
     * @param  fieldName 属性名称
     * @param  o 操作对象
     * @return Object 属性值
     */

    private Object getFieldValueByName(String fieldName, Object o)
    {
        try
        {
            String firstLetter = fieldName.substring(0, 1).toUpperCase();
            String getter = "get" + firstLetter + fieldName.substring(1);
            Method method = o.getClass().getMethod(getter, new Class[]{});
            Object value = method.invoke(o, new Object[] {});
            return value;
        } catch (Exception e)
        {
            System.out.println("属性不存在");
            return null;
        }
    }

    private String[] getFieldStrValueByName(String[] fieldNameList, Object o)
    {
        String[] ret=new String[fieldNameList.length];
        for(int i=0;i<fieldNameList.length;i++)
        {
            Object _temp=getFieldValueByName(fieldNameList[i],o);
            ret[i]=_temp==null?null:_temp.toString();
        }
        return ret;
    }

    public List<Map<String,Object>> getSqlQueryResult(String str)
    {
        return krecordEverydayMapper.getSqlQueryResult(str);
    }
}

